package com.han.spider.safecounty;

import com.han.spider.safecounty.entity.DeviceEntity;
import com.han.spider.safecounty.entity.RegionEntity;
import com.han.spider.safecounty.util.DateUtil;
import com.han.spider.safecounty.util.Persistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;

/**
 * @Author: Hanjiafeng
 * @Date: 2020/5/23
 * @Desc:
 */
public class Select extends VideoMonitor {
    private static final Logger LOGGER = LoggerFactory.getLogger(VideoMonitor.class);
    private final Map<Integer, RegionEntity> zhenMap;
    private final Map<Integer, RegionEntity> cunMap;
    private final Map<Integer, RegionEntity> zhuangMap;
    private final Map<String, DeviceEntity> deviceMap;
    private final String storagePath = "C:\\Users\\Administrator\\Desktop\\SafeCounty\\data";
    private final String parameterPath = storagePath + "\\parameter";
    private final String warehousePath = storagePath + "\\warehouse";

    public Select(String cookie) {
        super(cookie);
        zhenMap = new HashMap<>(10);
        cunMap = new HashMap<>(10);
        zhuangMap = new HashMap<>(10);
        deviceMap = new HashMap<>(10);
        LOGGER.info("初始化存储目录成功:" + storagePath);
    }

    public void find() {
        selectTodayInfo();
        serializeToLocal();
        compare();
    }

    /**
     * 将几个map都序列化到本地
     */
    public void serializeToLocal() {
        try {
            Persistence.serializeToLocal(parameterPath, DateUtil.getToday() + " zhenMap.out", zhenMap);
            Persistence.serializeToLocal(parameterPath, DateUtil.getToday() + " cunMap.out", cunMap);
            Persistence.serializeToLocal(parameterPath, DateUtil.getToday() + " zhuangMap.out", zhuangMap);
            Persistence.serializeToLocal(parameterPath, DateUtil.getToday() + " deviceMap.out", deviceMap);
            LOGGER.info("村镇设备信息本地序列化成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Object readFromLocal(String fileName) {
        return Persistence.serializeFromLocal(parameterPath, fileName);
    }

    @SuppressWarnings("unchecked")
    public void compare() {
        //对比日期
        String beyondDay = DateUtil.getYesterday();
        Map<String, DeviceEntity> yesterdayDeviceMap = new HashMap<>(1);
        try {
            yesterdayDeviceMap = (Map<String, DeviceEntity>) readFromLocal(beyondDay + " deviceMap.out");
            yesterdayDeviceMap = Objects.requireNonNullElse(yesterdayDeviceMap, new HashMap<>(1));
            LOGGER.info("反序列化" + beyondDay + "村镇设备信息成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        Set<String> yesterdayDeviceKeySet = yesterdayDeviceMap.keySet();
        List<String> list = new ArrayList<>(yesterdayDeviceKeySet);
        Map<String, DeviceEntity> differenceDeviceMap = new HashMap<>(deviceMap);
        //从今天的设备集合中删除昨天的
        for (int i = list.size() - 1; i >= 0; i--) {
            String yesterdayCode = list.get(i);
            differenceDeviceMap.remove(yesterdayCode);
        }
        supplement(differenceDeviceMap, DateUtil.getToday() + " 设备变化记录.txt");
        supplement(deviceMap, DateUtil.getToday() + " 设备.txt");
    }

    private void supplement(Map<String, DeviceEntity> differenceDeviceMap, String fileName) {
        Map<Integer, RegionEntity> allRegionMap = new HashMap<>(1);
        allRegionMap.putAll(zhenMap);
        allRegionMap.putAll(cunMap);
        allRegionMap.putAll(zhuangMap);
        differenceDeviceMap.forEach((code, deviceEntity) -> {
            String deviceName = null;
            String zhenName = null;
            String cunName = null;
            String zhuangName = null;
            try {
                deviceName = deviceEntity.getName();
                RegionEntity lastRegionEntity = allRegionMap.get(deviceEntity.getGroupId());
                LevelEnum levelEnum = lastRegionEntity.getLevelEnum();
                if (levelEnum.equals(LevelEnum.ZHUANG)) {
                    zhuangName = lastRegionEntity.getName();
                    lastRegionEntity = allRegionMap.get(lastRegionEntity.getParentId());
                    levelEnum = lastRegionEntity.getLevelEnum();
                }
                if (levelEnum.equals(LevelEnum.CUN)) {
                    cunName = lastRegionEntity.getName();
                    lastRegionEntity = allRegionMap.get(lastRegionEntity.getParentId());
                    levelEnum = lastRegionEntity.getLevelEnum();
                }
                if (levelEnum.equals(LevelEnum.ZHEN)) {
                    zhenName = lastRegionEntity.getName();
                }
                //拼接字符串
                String deviceInfo = joint(zhenName, cunName, zhuangName, deviceName, code);
                //删除不可见字符串
                deviceInfo = deviceInfo.replaceAll("\\s", "");
                Persistence.writeToLocal(deviceInfo, warehousePath, fileName, true);
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.info(zhenName + "->" + cunName + "->" + zhuangName + "->" + deviceName + "写入本地失败");
            }
        });
        LOGGER.info("\"" + fileName + "\"写入本地成功");
    }

    private String joint(String zhen, String cun, String zhuang, String deviceName, String deviceCode) {
        StringBuilder jointSb = new StringBuilder();
        if (!Objects.isNull(zhen)) {
            jointSb.append("镇:").append(zhen);
        }
        if (!Objects.isNull(cun)) {
            jointSb.append(",村:").append(cun);
        }
        if (!Objects.isNull(zhuang)) {
            jointSb.append(",庄:").append(zhuang);
        }
        if (!jointSb.toString().isEmpty()) {
            jointSb.append(",设备名称:").append(deviceName).append(",设备编码:").append(deviceCode);
        } else {
            jointSb.append("未找到层级结构,设备名称:").append(deviceName).append(",设备编码:").append(deviceCode);
        }

        return jointSb.toString();
    }

    public void selectTodayInfo() {

        RegionEntity xianRegionEntity = new RegionEntity(40485, "蒙城平安乡镇户户联防平台", LevelEnum.XIAN, TypeEnum.NO_DIRECT_DEVICE, null, null, null, "xl43oujh");
        try {
            zhenMap.putAll(selectRegionNew(xianRegionEntity));
            zhenMap.forEach((zhenId, zhenRegionEntity) -> {
                try {
                    TypeEnum type = zhenRegionEntity.getTypeEnum();
                    if (type.equals(TypeEnum.NO_DIRECT_DEVICE)) {
                        cunMap.putAll(selectRegionNew(zhenRegionEntity));
                    } else if (type.equals(TypeEnum.DIRECT_DEVICE)) {
                        deviceMap.putAll(selectDevice(zhenRegionEntity));
                    }
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            });
            LOGGER.info("镇级目录检索完成:" + zhenMap.size());
            cunMap.forEach((cunId, cunRegionEntity) -> {
                try {
                    TypeEnum type = cunRegionEntity.getTypeEnum();
                    if (type.equals(TypeEnum.NO_DIRECT_DEVICE)) {
                        zhuangMap.putAll(selectRegionNew(cunRegionEntity));
                    } else if (type.equals(TypeEnum.DIRECT_DEVICE)) {
                        deviceMap.putAll(selectDevice(cunRegionEntity));
                    }
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            });
            LOGGER.info("村级目录检索成功:" + cunMap.size());
//            遍历庄下面的设备
            zhuangMap.forEach((zhuangId, zhuangRegionEntity) -> {
                try {
                    deviceMap.putAll(selectDevice(zhuangRegionEntity));
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            });
            LOGGER.info("庄级目录检索成功:" + zhuangMap.size());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
